#!/usr/bin/perl 
#
#Check HOME
# Este script fara um check na home, verificando integridade de links de diversas urls da home. 

use strict ;
use IO::Socket;
use File::Basename;
use Sys::Hostname;
use WWW::Mechanize ;



my $remote_host = "www.uol.com.br";
my $remote_port = 80 ;

my $logDate = `/bin/date +%Y%m%d`;
chomp $logDate ;

my $errorLog = "/export/logs/check/monit_home2-${logDate}.log";

my $hostname .= "check_home.adm.uol.intranet";
my $scriptname=basename("$0");

my %urls = ();
my %failUrls = ();
my %timeouts = ();

my $TRUE = 0 ;
my $FALSE = 1; 

my $statusOK = 0;
my $statusWarning = 1;
my $statusCritical = 2;

my $maxRetries = 3; 

sub timestamp
{
    my $tstamp = "[". time()."]";

    return ( $tstamp );
}

sub checkOldProcess ()
{
   my $myself = $0 ;

   my $mypid = $$ ;

   my $myppid = getppid();

   my @output = `ps -ef | grep $myself |egrep -v \"$mypid|$myppid\" |grep -v grep`;

   #print "$myself $mypid $myppid\n";


   foreach my $line ( @output )
   {
       #print "$line\n";
       my ($f1, $pid, @rest ) = split ( /[\s|\t]+/ , $line );
       next if $pid == "" ;
       #print "$pid\n";
       my $out = `kill $pid`;
   }

}


sub printResult ()
{
   my $msg = shift();
  
   my $tstamp = timestamp();


   my $message = "$tstamp PROCESS_SERVICE_CHECK_RESULT;$hostname;Check Full HOME;$msg";

   #my $out = `/bin/logger -p local5.info \"$message\"`;

   open ( ERRORLOG, ">>$errorLog" ) or die "Can't write to file: $!";
   print  ERRORLOG "$message\n";
   close ( ERRORLOG );

   #print "$message\n";
}

sub abortResult ()
{
   my $msg = shift();

   my $tstamp = timestamp();


   my $message = "$tstamp PROCESS_SERVICE_CHECK_RESULT;$hostname;Check Full HOME;$msg";

   #my $out = `/bin/logger -p local5.info \"$message\"`;

   #open ( ERRORLOG, ">>$errorLog" ) or die "Can't write to file: $!";
   #print  ERRORLOG "$message";
   #close ( ERRORLOG );

   print "$message\n";
   die "$message\n";
}

sub checkUrl($$)
{
   my $isOk = $TRUE; 
   my $message = "ok"; 
   my $hostname = shift(); 
   my $uri = shift(); 

   if ( $uri =~ /(.*)\|/ )
   {
      $uri = $1 ;
   }

   #print "URL $hostname$uri  \n";

   my $remote_host = $hostname;
   my $remote_port = 80 ;
   
   my $socket = IO::Socket::INET->new(PeerAddr => $remote_host,
                                      PeerPort => $remote_port,
                             	      Proto    => "tcp",
				      Type     => SOCK_STREAM,
				      Timeout => 40 )
   or my $failure  =  "$@"; 
      
   if ( $failure  )
   {
      if ( ! exists ($timeouts{$hostname}) )  
      {
           $timeouts{$hostname} = 1 ;
           $isOk = $FALSE;
           $message .= "( Error Connecting to $hostname $failure )" ; 
       }
   }
   else
   { 
      if ( $hostname =~ /mixbrasil.uol.com.br/ || $hostname =~ /portalimprensa\.uol\.com\.br/ || $hostname =~ /www2\.uol\.com\.br/ || $hostname =~ /carsale\.uol\.com\.br/ || $hostname =~ /shopping.uol.com.br/ )
      {
          print $socket "GET $uri HTTP/1.1\nUser-Agent: ChechHome\nHOST: $hostname\n\n";
      }
      else
      {
          print $socket "HEAD $uri HTTP/1.1\nUser-Agent: ChechHome\nHOST: $hostname\n\n";
          print $socket "\n";
      }
   
      my $redirect = 0 ;
   
      while ( <$socket> )
      {
          my $response = $_ ;
          #print "$response\n";
          if ( $response =~ /HTTP\/1.1 200 OK/ )
          {
             #&printResult( "OK hostname \"$hostname$uri\"");
             last ;
          }
          elsif ( $response =~ /HTTP\/1.1 30[1|2|7]\s/ )
          {
               $redirect = 1 ;
	       #print "REDIRECT\n$response\n";
          }
          elsif ( $response =~ /HTTP\/1.1 (\d+)\s/ )
          {
              my $code = $1 ;
              $isOk = $FALSE;
              my $url = "${hostname}$uri" ;
              $message = "( HTTP ERROR CODE $code for host:  ${hostname}$uri  - $urls{$url} )" ; 
          }
      
          if ( $redirect == 1 and $response =~ /Location: (.*)/ )
          {
             my $location = $1 ;
             if ( $location =~ /e.busca.uol.com.br/ )
	     {
                 $isOk = $FALSE;
                 my $url = "${hostname}$uri" ;
                 $message = "( HTTP ERROR CODE 302 for host: ${hostname}$uri - $location  - $urls{$url})" ; 
	     }
	     last ;
          }
      }
      close($socket);
      return ($isOk,$message) ; 
   }
}

&checkOldProcess  ;

## Usa o mechanize para baixar a home e separar links
my $mech = WWW::Mechanize->new();

$mech->get("http://www.uol.com.br");

my @links =  $mech->find_all_links();


foreach my $link (@links )
{
   my $url = $link->url() ; 
   my $url_text = "[". $link->text() ."]";
   chomp $url ;
 
   if ( $url !~  /^http/ )
   {
       $url = "http://$url";
   }
 

   #if ( $url =~ /http:\/\/click\.uol\.com\.br\/.*\&u\=([\w|\=|\:|\.|\&|\?|\/|\-|\;|\_|\#]+)[\"|\s|\>|\|\n]{1}/ )
   if ( $url =~ /http:\/\/click\.uol\.com\.br\/.*\&u\=([\w|\=|\:|\.|\&|\?|\/|\-|\;|\_|\#]+)/ )
   {
       $url = $1;

       next if ( $url !~ /http:\/\/[\w|\d|\-]+\.[\w|\d|\-]+\..*/ );

       if ( $url =~ /(http:\/\/.*)\|http:\/\// )
       {
             $url = $1 ;
       }

       if ( $url !~  /clicklogger\.rm/ and $url !~ /^https/ )
       {
          #print "URL $url\n";
	  if ( ! exists $urls{$url} )
	  {
	      $urls{$url} = $url_text ;
	  }
          else 
          {
               $urls{$url} .= $url_text ;
          }
       }
    }

    if ( $url !~ /javascript/ and  $url !~ /bn\.uol\.com\.br/ and $url !~ /clicklogger\.rm\.uol\.com\.br/ )
    {
       #print "URL $url\n";
       if ( ! exists $urls{$url} )
       {
            $urls{$url} = $url_text ;
       }
       else 
       {
            $urls{$url} .= $url_text ;
       }
    }
    elsif ( $url =~ /href\=(http\:[\w|\=|\:|\.|\&|\?|\/|\-|\;|\_|\#]+)[\"|\s|\>|\|]{1}/ )
    {
       my $url = $1 ;
       if ( $url !~ /javascript/ and  $url !~ /bn\.uol\.com\.br/ and $url !~ /clicklogger\.rm\.uol\.com\.br/ and $url !~ /www2\.uol\.com\.br/ and $url !~ /mixbrasil\.uol\.com\.br/)
       #if ( $url !~ /javascript/ and  $url !~ /bn\.uol\.com\.br/ and $url !~ /clicklogger\.rm\.uol\.com\.br/ and $url !~ /www2\.uol\.com\.br/)
       {
          #print "URL $url\n";
	  if ( ! exists $urls{$url} )
	  {
	      $urls{$url} = $url_text ;
	  }
          else 
          {
               $urls{$url} .= $url_text ;
          }
       }
    }
}

my $failMessage = "";

my $resultOK = $TRUE ; 
   
foreach my $url (keys %urls )
{
   next if $url =~/polls.folha.com.br/;
   next if $url =~ /http:\/\/click\.uol\.com\.br\/.*\&u\=/ ;
   next if $url =~ /http:\/\/\#/ ;
   next if $url =~/www2.uol.com.br/;
   next if $url =~/jogos360.uol.com.br/;

  
   my $hostname = "";
   my $uri = "";


   if ($url =~ /http\:\/\/([\w|\-|\_|\.]+)(\/.*)/)
   {
      $hostname = $1 ;
      $uri = $2 ;
   }
   next if ( exists ($timeouts{$hostname}) );
   next if $hostname eq "";

   my ($result,$resultmessage) = checkUrl($hostname, $uri ); 
   if ( $result == $FALSE )
   {
        my $failRetries = 1; 

        my $failmsg = $resultmessage ; 
 
        for ( my $i = 1 ; $i <= $maxRetries ; $i++ )
        {
            #print "$i "; 
            ($result,$resultmessage) = checkUrl($hostname, $uri ); 

            if ( $result == $FALSE )
            {
                 $failRetries ++ ; 
            }
        }

        if ( $failRetries / $maxRetries > 0.5 )
        {
            #print "$failRetries / $maxRetries". $failRetries / $maxRetries."\n"; 
            $failMessage .= $failmsg ;
            $resultOK = $FALSE ; 
            #print "$result, $failmsg\n"; 
        }
              
   }
}


if ( $resultOK == $TRUE )
{
   &printResult ("$statusOK; Everything is fine");
}
else
{
   &printResult ( "$statusCritical;$failMessage" );
}
